<template>
  <div v-loading="state.loading">
    <div class="opts">
      <div class="opt-item">
        <label for="">间隔</label>
        <input type="number" v-model="state.size" />
      </div>
    </div>
    <div class="btns">
      <button class="btn" @click="analyse">分析</button>
      <button class="btn" @click="clean">清除</button>
    </div>
  </div>
</template>

<script setup>
  import { onBeforeUnmount, onMounted, reactive } from 'vue';
  import useDraw, { DrawType } from '@/hooks/useDraw';
  import * as Cesium from 'cesium';
  import { AspectAnalysis } from 'cgak';
  import { vLoading } from 'element-plus';
  import { ElNotification } from 'element-plus';

  const state = reactive({
    tiped: false,
    size: 50,
    loading: false,
  });

  const entities = [];
  const analyser = new AspectAnalysis(window.viewer.terrainProvider, state.size);

  const { drawStart, drawStop, drawClear } = useDraw(window.viewer, {
    type: DrawType.POLYGON,
    clampToGround: true,
    finishCallback: async positions => {
      console.log('finish drawing');
      let pts = [...positions, positions[0]];

      if (pts.length >= 3) {
        state.loading = true;
        await analyser
          .analyse(pts)
          .then(res => {
            console.log(res);
            const { aspects, positions } = res;
            positions.forEach((rec, index) => {
              const angle = aspects[index];
              const cellEntity = window.viewer.entities.add(
                new Cesium.Entity({
                  rectangle: {
                    coordinates: Cesium.Rectangle.fromCartesianArray(rec),
                    material: new Cesium.ImageMaterialProperty({
                      image: './static/material/arrow.png',
                      transparent: true,
                    }),
                    rotation: Cesium.Math.toRadians(angle), // 设置旋转角度
                    stRotation: Cesium.Math.toRadians(angle), // 纹理坐标旋转
                  },
                })
              );
              entities.push(cellEntity);
            });
          })
          .finally(() => {
            state.loading = false;
          });
        drawClear();
      }
    },
  });

  const analyse = () => {
    if (!state.tiped) {
      ElNotification({ message: '点击鼠标左键绘制视线，每两点分析一次，点击右键结束。', duration: 5000 });
      state.tiped = true;
    }
    drawStart();
  };

  onMounted(() => {
    window.viewer.scene.globe.depthTestAgainstTerrain = true;
  });

  const clean = () => {
    drawStop();
    drawClear();
    analyser?.clear();
    while (entities.length > 0) {
      window.viewer.entities.remove(entities.pop());
    }
  };

  onBeforeUnmount(() => {
    clean();
  });
</script>
